package com.conjane.algo.array_list;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class FindAllPairsAccordingToGivenNumberInArray {

    /**
     * 暴力方法：双重循环
     *
     * @param array
     * @param givenNumber
     */
    public static void findPairsByBruteForce(int[] array, int givenNumber) {
        for (int i = 0; i < array.length; i++) {
            int first = array[i];
            for (int i1 = i + 1; i1 < array.length; i1++) {
                int second = array[i1];
                if (givenNumber == first + second) {
                    System.out.println("[" + first + "," + second + "]");
                }
            }
        }
    }

    public static void printPairsUsingTwoPointers(int[] array, int givenNumber) {
        if (array.length < 2) {
            return;
        }
        Arrays.sort(array);
        int left = 0;
        int right = array.length - 1;
        while (left < right) {
            int sum = array[left] + array[right];
            if (sum == givenNumber) {
                System.out.printf("(%d, %d) %n", array[left], array[right]);
                left = left + 1;
                right = right - 1;
            } else if (sum < givenNumber) {
                left = left + 1;
            } else {
                right = right - 1;
            }
        }
    }

    public static void printPairsUsingSet(int[] array, int givenNumber){
        if(array.length < 2){
            return;
        }
        Set set = new HashSet(array.length);

        for(int value : array){
            int target = givenNumber - value;

            // if target number is not in set then add
            if(!set.contains(target)){
                set.add(value);
            }else {
                System.out.printf("(%d, %d) %n", value, target);
            }
        }
    }


    public static void main(String[] args) {
        int[] array = new int[]{1, 2, 7, 3, 5, 6, 11, 9};
        int givenNumber = 19;
        findPairsByBruteForce(array, givenNumber);
    }
}
